const express = require('express')
const Vue = require('vue')
const fs = require('fs')
const cookieParser = require('cookie-parser') 
const { createBundleRenderer } = require('vue-server-renderer')
const setupDevServer = require('./build/setup-dev-server.js')

const server = express()
server.use('/dist', express.static('./dist'))
server.use('/static', express.static('./static'))
server.use(cookieParser())

let renderer, onReady
const isProd = process.env.NODE_ENV === 'production'

if (isProd) {
  const serverBundle = require('./dist/vue-ssr-server-bundle.json')
  const clientManifest = require('./dist/vue-ssr-client-manifest.json')
  const template = fs.readFileSync('./index.template.html', 'utf-8')

  renderer = createBundleRenderer(serverBundle, {
    runInNewContext: false,
    template,
    clientManifest
  })
} else {
  onReady = setupDevServer(server, ({ serverBundle, clientManifest, template }) => {
    renderer =  createBundleRenderer(serverBundle, {
      runInNewContext: false,
      template,
      clientManifest
    })
  })
}

server.get('*', async (req, res) => {
  try {
    if (!isProd) await onReady
    const html = await renderer.renderToString({
      url: req.url,
      title: '拉勾教育',
      cookies:req.cookies
    })
    res.set('Content-Type', 'text/html; charset=utf8;')
    res.end(html)

  } catch (error) {
    res.sendStatus(error.code || 500)
  }
})

server.listen(3000, () => {
  console.log('Server running at port 3000');
})